package com.harmonyos.samples.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.harmonyos.samples.bean.cache.CacheType;
import com.harmonyos.samples.bean.repository.Result;
import org.apache.http.client.methods.HttpGet;

import java.io.*;
import java.nio.file.Files;
import java.util.List;

public class DataReader {
    public List<Result> onlineData(String configUrl, String fileName) throws IOException {
        if (CacheUtils.getInstance().update(CacheType.Config, "config")) {
            String config = "";
            String responseStr = HttpRequest.getInstance().executeGet(new HttpGet(configUrl));
            if (responseStr != null) {
                if (!responseStr.startsWith("<!DOCTYPE html>") && !responseStr.startsWith("<html")) {
                    config = responseStr;
                }
            }
            if (config.isEmpty()) {
                return null;
            }
            ObjectMapper mapper = new ObjectMapper();
            List<Result> resultList = mapper.readValue(config, new TypeReference<>() {
            });
            File localFile = new File(InsertUtils.getCacheDirectory(), fileName);
            Files.writeString(localFile.toPath(), config);
            CacheUtils.getInstance().add(CacheType.Config, "config");
            return resultList;
        } else {
            return localData(fileName);
        }
    }

    public List<Result> localData(String fileName) throws IOException {
        File localFile = new File(InsertUtils.getCacheDirectory(), fileName);
        if (!localFile.exists()) {
            return null;
        }
        String config = Files.readString(localFile.toPath());
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(config, new TypeReference<>() {
        });
    }

    public List<Result> packageData() throws IOException {
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("config.json");
        if (inputStream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder config = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                config.append(line).append("\n");
            }
            reader.close();
            inputStream.close();
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(config.toString(), new TypeReference<>() {
            });
        }
        return null;
    }
}
